#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
    Mat img1 = imread("image.jpg");
    Mat img2 = imread("mask.jpg");
    Mat roi = img1(Range(0, img2.rows), Range(0, img2.cols));
    Mat img2gray;
    cvtColor(img2, img2gray, COLOR_BGR2GRAY);

    Mat mask;
    threshold(img2gray, mask, 10, 255, THRESH_BINARY);
    Mat mask_inv, mask1;
    bitwise_not(mask, mask_inv);
    Mat img1_bg;
    bitwise_and(roi, roi, img1_bg, mask_inv);
    Mat img2_fg;
    bitwise_and(img2, img2, img2_fg, mask);
    Mat destination;
    add(img1_bg, img2_fg, destination);
    destination.copyTo(img1(Range(0, img2.rows), Range(0, img2.cols)));

    imshow("mask", mask);
    waitKey(0);
    imshow("mask_inv", mask_inv);
    waitKey(0);
    imshow("img1_bg", img1_bg);
    waitKey(0);
    imshow("img2_fg", img2_fg);
    waitKey(0);
    imshow("destination", destination);
    waitKey(0);
    imshow("img1", img1);
    waitKey(0);
    return 0;
}